package DoublyListSentinel;

import java.util.Iterator;

public class DoubleList implements Iterable<Integer> {
    private Node hand;
    private Node tail;
    static class Node{
        public Node prev;
        public int value;
        public Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    //构造器来初始化头节点、尾节点
    public DoubleList() {
        Node hand = new Node(null,0,null);
        Node tail = new Node(null, -1, null);
        hand.next = tail;
        tail.prev = hand;
    }

    //根据索引来查找节点
    private Node findNode(int index) {
        int i = -1;
        for (Node p = hand; p != tail ;p = p.next, i++ ) {
            if (i == index){
                return p;
            }
        }
        return null;
    }

    //根据索引来插入节点
    public void insect(int index, int value)  {
        Node prev = findNode(index - 1);
        if (prev == null) {
            throw new RuntimeException("索引输入不当！");
        }
        Node next = prev.next;
        Node node = new Node(prev,value,next);
        prev.next = node;
        next.prev = node;
    }

    //头插节点
    public void addFirst(int value) {
        insect(0,value);
    }

    //尾插节点
    public void addLast(int value) {
        Node last = tail.prev;
        Node node = new Node(last , value , tail);
        last.next = node;
        tail.prev = node;
    }

    //根据索引来删除节点
    public void remove(int index) {
        Node prev = findNode(index - 1);
        if (prev == null) {
            throw new RuntimeException("索引输入不当！！！");
        }
        Node remove = prev.next;
        if (remove == null) {
            throw new RuntimeException("索引输入不当！！！");
        }
        Node next = remove.next;

        prev.next = next;
        next.prev = prev;
    }

    //尾删节点
    public void removeLast() {
        Node last = tail.prev;
        if (last == hand) {
            throw  new RuntimeException(" 索引输入不当 ！");
        }
        Node prev = last.prev;
        prev.next = tail;
        tail.prev = prev;
    }

    //头删节点
    public void removeFirst() {
        remove(0);
    }

    //实现迭代器

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = hand.next;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public Integer next() {
                int k = p.value;
                p = p.next;
                return k;
            }
        };
    }
}
